﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Tisonet.Dobrak.Domain.Models;
using Tisonet.Dobrak.Domain.Services.Downloaders;
using HtmlAgilityPack;

namespace Tisonet.Dobrak.Domain.Services.Projections
{
    public class DobrakProjectionsProvider : IProjectionsProvider
    {
        private const string DOBRAK_WEB_URL = "http://www.kinonadobraku.cz/";

        private readonly IDownloader _downloader;

        public DobrakProjectionsProvider(IDownloader downloader)
        {
            if (downloader == null)
            {
                throw new ArgumentNullException("downloader");
            }

            _downloader = downloader;
        }

        public async Task<IEnumerable<Projection>> GetProjectionsAsync()
        {
            Uri sourceWebUri = new Uri(DOBRAK_WEB_URL);

            Stream stream = await _downloader.DownloadAsync(sourceWebUri);

            using (stream)
            {
                IEnumerable<Projection> projections = ParseProjectionFromHtmlStream(stream);

                return projections;
            }
        }


        private IEnumerable<Projection> ParseProjectionFromHtmlStream(Stream htmlStream)
        {
            var doc = new HtmlDocument();
            
            doc.Load(htmlStream, Encoding.UTF8);

            var parser = new DobrakHtmlParser(doc.DocumentNode);

            return parser.ParseProjections();
        }
    }
}
